<?php declare(strict_types=1);
$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
    'id'       => $di->request->params('id'),
];


if ($params['admin_id'] !== null) {
    $roleIds = $di->auth->getChildrenRoleIds($params['admin_id'], true);
    if (!in_array($params['id'], $roleIds)) throw new LogicException('没有权限查看', 99999);
}

$row = $di->db->find('select * from admin_role where id=:id', [
    'id' => $params['id'],
]);

if (!$row) throw new LogicException('记录不存在');

$textList = [
    'status' => [1 => '正常', 0 => '隐藏'],
];

$row['status_text'] = $textList['status'][$row['status']];

$resourceIds = array_column($di->db->query('select resource_id from admin_role_resource_access where role_id=:role_id', [
    'role_id' => $params['id'],
]), 'resource_id');

if (in_array(0, $resourceIds)) {
    $resources = $di->db->query('select * from admin_resource order by weigh,path');
} else {
    $resources = $di->db->query('select * from admin_resource where id in (:id) order by weigh,path', [
        'id' => $resourceIds,
    ]);
}

$resourceIds = array_column($resources, 'id');

foreach ($resources as &$resource) {
    if (!in_array($resource['pid'], $resourceIds)) {
        $resource['pid'] = 0;
    }
    $resource['name'] = $resource['title'];
}

$row['resources'] = $resources;

return [
    'row' => $row,
];